#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time   : 2023-08-21 21:22
# @Author : hard work
# @File    : ntp_error.py
# @Description :
"""change version to v3"""
import ntplib

ntpserver_list = ['10.11.0.50', '10.11.0.217', '10.11.0.208', '10.11.0.218']

def get_ntp_time(ntp_server_url):
    ntp_client = ntplib.NTPClient()
    ntp_stats = ntp_client.request(ntp_server_url, version=3, timeout=10)
    return ntp_stats


def calc_offset(ntpserver):
    """    SNTP 时间同步准确度应优于 10ms。
              server direct pc , offset = A
              server direct 217, offset = A
              217 -> 208, offset B, A - B
              208 -> 218, offset C, B - C
    """
    pc_server_offset = get_ntp_time(ntpserver[0]).offset
    pc_dut217_offset = get_ntp_time(ntpserver[1]).offset
    dut217_dut208_offset = get_ntp_time(ntpserver[2]).offset
    dut208_dut218_offset = get_ntp_time(ntpserver[3]).offset
    print("ntp-server与PC{}的offset -> ".format(ntpserver[0]), pc_server_offset)
    print("ntp-server与DUT{}的offset -> ".format(ntpserver[1]), pc_dut217_offset)
    print("ntp-server与DUT{}的offset -> ".format(ntpserver[2]), dut217_dut208_offset)
    print("ntp-server与DUT{}的offset -> ".format(ntpserver[3]), dut208_dut218_offset)
    avg = (pc_server_offset + pc_dut217_offset + dut217_dut208_offset + dut208_dut218_offset) /4
    print("链路平均offset： ", avg)
    print(pc_server_offset - avg)

def all_offset():
    for ntpserver in ntpserver_list:
        ntp_offset = get_ntp_time(ntpserver).offset
        print(ntpserver + '当前NTP同步offset值为：' + str(ntp_offset))
        if ntp_offset > 0.5 or ntp_offset < -0.5:
            print(ntpserver + '目前始终偏移量较高，当前NTP同步offset值为：' + str(ntp_offset))
        print(50 * "-")


if __name__ == '__main__':

    calc_offset(ntpserver_list)



